package nettyteach.endecoder;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 *
 * 客户端启动类
 */
public class AppClienEnDeCoder {
    private final String host;
    private final int port;

    public AppClienEnDeCoder(String host, int port) {
        this.host = host;
        this.port = port;
    }
    public void run()throws Exception{
        /**
         * 配置相应的参数，提供链接到远端的方法
         *
         */
        EventLoopGroup group =new NioEventLoopGroup();//I/o线程池
        try {
            Bootstrap bs=new Bootstrap();//客户端启动辅助对象
            bs.group(group)
                    .channel(NioSocketChannel.class)//实例化一个通道
                    .remoteAddress(new InetSocketAddress(host,port))//指定远端
                    .handler(new InitializerClientEndeCoder());
            //获取结果事件，连接到远程节点，等待连接完成
            ChannelFuture future=bs.connect().sync();



            //阻塞操作，closeFuture()开启了一个channel的监听器（这期间channel在进行各项工作），直到链路断开
            future.channel().closeFuture().sync();
        }finally {
             group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args)throws Exception {
        new AppClienEnDeCoder("127.0.0.1",18080).run();
    }
}
